# coding: utf8
import random
import datetime
from umeng_tool.analyse.utils import DatetimeUtils

class TimeNode:
    def __str__(self):
        return '%s (%s, %s] %s' % (self.start_time, self.min_limit, self.max_limit, self.percent)
    
    def __init__(self, hour, percent, count, min_limit, max_limit):
        self.hour = hour
        self.percent = percent
        self.count = count
        self.min_limit = min_limit  # 概率区间左值
        self.max_limit = max_limit  # 概率区间右值
        
    def __contains__(self, ratio):
        return self.min_limit < ratio <= self.max_limit

    @property
    def start_time(self):
        """
        :return: 时间节点
        :rtype: datetime
        """
        now = DatetimeUtils.now_local()
        return datetime.datetime(
            year=now.year,
            month=now.month,
            day=now.day,
            hour=self.hour,
            minute=0,
            second=0,
            tzinfo=now.tzinfo
        )
    
    def make_time(self):
        """
        :return: (时间节点，在线时长单位秒)
        :rtype: tuple
        """
        return self.start_time + datetime.timedelta(minutes=random.randint(1, 60)), random.randint(30, 5 * 60)

class AccessData:
    def __init__(self, file_path='f:/md.db'):
        with open(file_path, 'r') as f:
            t = []
            max_count = 100
            for line in f:
                line = line.split(' ')
                hour = int(line[0])
                percent = round(float(line[1]), 2)
                count = int(max_count * percent)
                t.append((hour, percent, count))

            index = 0
            p = []
            for i in t:
                min_limit = index
                index += i[2]
                max_limit = index
                p.append({
                    'hour': i[0],
                    'percent': i[1],
                    'count': i[2],
                    'min_limit': min_limit,
                    'max_limit': max_limit,
                })
                
            x = []
            for i in p:
                x.append(TimeNode(i['hour'], i['percent'], i['count'], i['min_limit'], i['max_limit']))
            self.data = x
            
    def make_key_times(self, node_count):
        n = []
        for i in range(node_count):
            ratio = random.randint(1, 99)
            for node in self.data:
                if ratio in node:
                    n.append(node.make_time())
                    break
        return sorted(n)


